<?php

namespace app\common\model;

use EasyWeChat\OfficialAccount\ShakeAround\PageClient;
use think\Db;
use think\Exception;
use think\facade\Config;
use think\Model;
use EasyWeChat\Factory;
use think\Log;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];

    /**
     * 获取个人URL
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }


    // 个人信息
    public function infos($data_array)
    {
        $url = config('fastadmin.api_url');
        // 用户信息
        $data = Db::name('user')
            ->where(['id' => $data_array['user_id']])
            ->field('id as user_id,is_vip,nickname,avatar,mobile,status,qrcode')
            ->find();
        //查询该用户领取会员卡没
        $user_card = Db::name('user_card')->where(['member_id' => $data['user_id']])->find();
        if (!$user_card || $user_card['status'] == 2) {
            $data['is_vip_card'] = 0; //跳转开通页面
        } elseif ($user_card['status'] == 1) {
            $data['is_vip_card'] = 1; //跳转领取会员卡
        } elseif ($user_card['status'] == 0) {
            $data['is_vip_card'] = 2; //跳转领取会员卡
        }

        if ($data['qrcode']) {
            $data['qrcode'] = $url . '/' . $data['qrcode'];
        } else {
            $data['qrcode'] = "";
        }
        $data['avatar'] = $data['avatar'] ? $url . $data['avatar'] : "";
        return $data;
    }


    /*
     * 
     */
    public function wxFillIn($params)
    {
        $data = [
            'avatar' => base64_image_content($params['avatar']),
            'nickname' => urldecode($params['nickname']),
        ];
        if (User::where('id', $params['user_id'])->update($data)) {
            return ['code' => 200, 'msg' => '成功', 'time' => '', 'data' => ''];
        } else {
            return ['code' => 201, 'msg' => '失败', 'time' => '', 'data' => ''];
        }
    }


    /*用户编辑*/
    public function editUser($params)
    {
        $user = Db::name('user')->where(['id' => $params['user_id']])->value('avatar');
        strpos($params['avatar'], 'https') === false ? $avatar = $params['avatar'] : $avatar = $user;
        $data = ['nickname' => urldecode($params['nickname']), 'avatar' => $avatar];
        // 用户信息
        $data = Db::name('user')->where(['id' => $params['user_id']])->update($data);
        if ($data) {
            return ['msg' => '编辑成功', 'data' => '', 'code' => 1];
        } else {
            return ['msg' => '编辑失败', 'data' => '', 'code' => 0];
        }
    }


    // 爱心池
    public function pools($data_array)
    {
        $url = config('fastadmin.api_url');
        // 爱心池
        $pool = Db::name('pool')->where('id', 1)->value('money');
        // 我的爱心值
        $integer = Db::name('user')->where('id', $data_array['user_id'])->value('score');
        // 我的捐赠
        $count_integer = Db::name('user_consume')->where(['user_id' => $data_array['user_id'], 'type' => 2, 'status' => 2, 'content' => '爱心值捐赠'])->sum('money');
        // 爱心值商品
        $goods = Db::name('goods')->where(['type' => 2, 'status' => 1])->field('id as goods_id,name,image,item')->select();
        if ($goods) {
            foreach ($goods as $key => $val) {
                $goods[$key]['image'] = $url . $val['image'];
                $item = json_decode($val['item'], true);
                $item = current($item);
                $goods[$key]['integer'] = $item['integral'];
            }
        }

        $result = ['pool' => $pool, 'integer' => $integer, 'count' => $count_integer, 'goods' => $goods];
        return $result;
    }


    // 我的优惠券
    public function coupons($data_array)
    {
        $page = $data_array['page'] ? $data_array['page'] : 1;
        $data = Db::name('user_coupons')
            ->alias('uc')
            ->join('coupons c', 'uc.cou_id = c.id')
            ->where(['uc.user_id' => $data_array['user_id'], 'uc.status' => 1])
            ->field('uc.id,uc.status,c.title,c.full,c.reduces,c.end_time,uc.create_time')
            ->order('create_time desc')
            ->page($page, 10)
            ->select();
        if ($data) {
            foreach ($data as &$val) {
                $val['end_time'] = date('Y-m-d H:i', $val['end_time']);
            }
        }

        return $data;
    }

    /*
     * 我的钱包
     * */
    public function wallets($data_array)
    {

        $page = $data_array['page'] ? $data_array['page'] : 1;
        $data = Db::name('user')->where('id', $data_array['user_id'])->field('money,score,rebate')->find();
        // 明细
        $detailed = [['type' => 1, 'name' => '余额明细'], ['type' => 2, 'name' => '爱心值明细'], ['type' => 3, 'name' => '返利明细'], ['type' => 4, 'name' => '提现明细']];
        $field = ['id,type,status,money,content,create_time'];
        foreach ($detailed as $key => &$val) {
            if ($val['type'] == 1) {
//                $val['detailed'] = Db::name('user_consume')->where(['user_id'=>$data_array['user_id'],'type'=>1])->field($field)->order('create_time desc')->page($page,10)->select();

                $consume = Db::name('user_consume')
                    ->alias('c')
                    ->join('user u', 'c.user_id = u.id')
                    ->where(['c.user_id' => $data_array['user_id']])
                    ->where('c.type', 'in', '1,4')
                    ->field('c.id,c.type,c.status,c.money,c.content,c.create_time')
                    ->buildSql();

                $cashout = Db::name('cashout')
                    ->alias('c')
                    ->join('user u', 'c.user_id = u.id')
                    ->where(['c.user_id' => $data_array['user_id'], 'c.state' => 1, 'c.form' => 2, 'c.status' => 2])
                    ->field('c.id,c.type,c.state as status,c.money,c.content,c.create_time')
                    ->buildSql();


                $order = Db::name('order')
                    ->alias('c')
                    ->join('user u', 'c.user_id = u.id')
                    ->where(['c.user_id' => $data_array['user_id'], 'c.status' => 6])
                    ->where('c.type', 'in', '1,2')
                    ->field('c.id,c.type,c.status,c.money,c.is_state as content,c.create_time')
                    ->buildSql();

                $sql = "(" . ($consume) . 'UNION All' . ($cashout) . 'UNION All' . ($order) . ")";

                $val['detailed'] = Db::table($sql . 'c')
                    ->field('id,type,status,money,content,create_time')
                    ->order('create_time desc')
                    ->page($page, 10)
                    ->select();

                foreach ($val['detailed'] as $k => $vo) {
                    if (empty($vo['content'])) {
                        $val['detailed'][$k]['content'] = "已退还";
                    }
                    if ($vo['status'] == 6) {
                        $val['detailed'][$k]['status'] = 1;
                    }
                }

            } elseif ($val['type'] == 2) {
                $val['detailed'] = Db::name('user_consume')->where(['user_id' => $data_array['user_id'], 'type' => 2])->field($field)->order('create_time desc')->page($page, 10)->select();
            } elseif ($val['type'] == 3) {
                $val['detailed'] = Db::name('user_consume')->where(['user_id' => $data_array['user_id'], 'type' => 3])->field($field)->order('create_time desc')->page($page, 10)->select();
            } elseif ($val['type'] == 4) {
                $val['detailed'] = Db::name('cashout')->where(['user_id' => $data_array['user_id'], 'state' => 1, 'form' => 1])->field('money,status,create_time,form,content')->order('create_time desc')->page($page, 10)->select();
            }
            if ($val['detailed']) {
                foreach ($val['detailed'] as &$val) {
                    $val['create_time'] = date('Y-m-d H:i', $val['create_time']);
                }
            }
        }

        $res = ['user' => $data, 'detailed' => $detailed];
        return $res;
    }


    /*
     * 地址列表
     * */
    public function addLists($data_array)
    {
        $page = $data_array['page'] ? $data_array['page'] : 1;
        $field = ['id,name,phone,provincial,city,area,address,status'];
        if (isset($data_array['type'])) {
            if (Db::name('user_address')->where(['user_id' => $data_array['user_id'], 'status' => 2])->count() == 1) {
                $data = Db::name('user_address')->where(['user_id' => $data_array['user_id'], 'status' => 2, 'is_delete' => 1])->field($field)->find();
            } else {
                $data = Db::name('user_address')->where(['user_id' => $data_array['user_id'], 'is_delete' => 1])->field($field)->order('create_time desc')->find();
            }
        } else {
            $data = Db::name('user_address')->where(['user_id' => $data_array['user_id'], 'is_delete' => 1])->order('create_time desc')->page($page, 10)->field($field)->select();
        }
        return $data;
    }


    /*
     * 我的地址
     * */
    public function address($data_array)
    {
        if (!$data_array['name']) return ['msg' => '请输入收货人', 'data' => '', 'code' => '0'];
        if (!$data_array['phone'] || !is_numeric($data_array['phone'])) return ['msg' => '请输入手机号或请输入数字', 'data' => '', 'code' => '0'];
        if (!preg_match('/^1[345789]\d{9}$/', $data_array['phone'])) return ['msg' => '手机号格式不正确', 'data' => '', 'code' => '0'];

        $data = ['user_id' => $data_array['user_id'], 'name' => $data_array['name'], 'phone' => $data_array['phone'], 'provincial' => $data_array['provincial'], 'city' => $data_array['city'], 'area' => $data_array['area'], 'address' => $data_array['address'], 'status' => $data_array['status'], 'create_time' => time()];

        if ($data_array['status'] == 2) {
//            if(Db::name('user_address')->where(['user_id'=>$data_array['user_id'],'status'=>2])->count() > 1)
//            {
            Db::name('user_address')->where(['user_id' => $data_array['user_id']])->update(['status' => 1]);
//            }
        }

        $res = Db::name('user_address')->insert($data);
        if ($res) {
            return ['msg' => '添加成功', 'data' => '', 'code' => 1];
        } else {
            return ['msg' => '添加失败', 'data' => '', 'code' => 0];
        }

    }


    /*
     * 地址返参
     * */
    public function addressResults($data_array)
    {
        $data = Db::name('user_address')->where('id', $data_array['id'])->field('id,name,phone,provincial,city,area,address,status')->find();
        return $data;
    }

    /*
     * 地址修改
     * */
    public function editAddress($data_array)
    {

        $data = ['user_id' => $data_array['user_id'], 'name' => $data_array['name'], 'phone' => $data_array['phone'], 'provincial' => $data_array['provincial'], 'city' => $data_array['city'], 'area' => $data_array['area'], 'address' => $data_array['address'], 'status' => $data_array['status'], 'update_time' => time()];

        if (Db::name('user_address')->where(['user_id' => $data_array['user_id'], 'status' => 2])->count() >= 1) {
            Db::name('user_address')->where(['user_id' => $data_array['user_id']])->update(['status' => 1]);
        }

        $res = Db::name('user_address')->where('id', $data_array['id'])->update($data);

        if ($res) {
            return ['msg' => '修改成功', 'data' => '', 'code' => 1];
        } else {
            return ['msg' => '修改失败', 'data' => '', 'code' => 0];
        }
    }


    /*
     * 删除地址
     * */
    public function addressDels($data_array)
    {
        $data = Db::name('user_address')->where('id', $data_array['address_id'])->update(['is_delete' => 2]);
        if ($data) {
            return ['msg' => '删除成功', 'data' => '', 'code' => 1];
        } else {
            return ['msg' => '删除失败', 'data' => '', 'code' => 0];
        }
    }


    /*
     * 捐赠爱心值
     * */
    public function integers($data_array)
    {
        $integer = Db::name('user')->where('id', $data_array['user_id'])->value('score');
        if (!is_numeric($data_array['integer']) || empty($data_array['integer'])) return ['msg' => '格式不正确或不能小于零', 'data' => '', 'code' => '0'];
        if ($integer < $data_array['integer']) return ['msg' => '您没有太多积分捐赠', 'data' => '', 'code' => '0'];

        Db::startTrans();
        try {
            Db::name('pool')->where('id', 1)->setInc('money', $data_array['integer']);
            Db::name('user')->where(['id' => $data_array['user_id']])->setDec('score', $data_array['integer']);
            $data = ['user_id' => $data_array['user_id'], 'type' => 2, 'status' => 2, 'money' => $data_array['integer'], 'content' => "爱心值捐赠", 'create_time' => time()];
            Db::name('user_consume')->insert($data);
            Db::commit();
            return ['msg' => '捐赠成功', 'data' => '', 'code' => 1];
        } catch (Exception $exception) {
            Db::rollback();
            return ['msg' => '捐赠失败', 'data' => '', 'code' => 0];
        }

    }

    /*
     * 提现
     * */
    public function withdraws($data_array)
    {
        $user = Db::name('user')->where('id', $data_array['user_id'])->field('nickname,money')->find();
        if (!is_numeric($data_array['money'])) return ['msg' => '格式不正确', 'data' => '', 'code' => 0];
        if ($data_array['money'] > $user['money']) return ['msg' => '提现余额不足', 'data' => '', 'code' => 0];
        if($data_array['money'] > 200){
            return ['msg' => '一次最多提现200元', 'data' => '', 'code' => 0];
        }
        $order_id = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
        $data = ['orderno' => $order_id, 'user_id' => $data_array['user_id'], 'nickname' => $user['nickname'], 'money' => $data_array['money'], 'type' => 1, 'status' => 1, 'state' => 1, 'form' => 1, 'content' => '提现记录', 'create_time' => time()];

        Db::startTrans();
        try {
            Db::commit();
            Db::name('user')->where('id', $data_array['user_id'])->setDec('money', $data_array['money']);
            Db::name('cashout')->insert($data);
            return ['msg' => '提交成功,待审核', 'data' => '', 'code' => 1];
        } catch (Exception $exception) {
            Db::rollback();
            return ['msg' => '提交失败', 'data' => '', 'code' => 0];
        }

    }


    /*
     * 提现返参
     * */
    public function withResults($data_array)
    {
        $money = Db::name('user')->where('id', $data_array['user_id'])->value('money');
        $usable = Db::name('user')->where('id', $data_array['user_id'])->value('money');
        $res = ['money' => $money, 'usable' => $usable];
        return $res;
    }


    /*
     * 充值
     * */
    public function recharges($data_array)
    {
        if (!is_numeric($data_array['money']) || empty($data_array['money'])) return ['msg' => '格式不正确或不能小于零', 'data' => '', 'code' => 0];
        // 调用config
        $config = config('wechat_pay');
        $app = Factory::payment($config);
        $user = Db::name('user')->where('id', $data_array['user_id'])->field('nickname')->find();
        $openid = Db::name('user')->where('id', $data_array['user_id'])->value('openid');

        // 生成订单
        $order = 'C' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
        // 生成数据
        $data = ['orderno' => $order, 'user_id' => $data_array['user_id'], 'nickname' => $user['nickname'], 'money' => $data_array['money'], 'type' => 1, 'status' => 1, 'state' => 1, 'form' => 2, 'create_time' => time(), 'content' => '充值记录'];
        Db::name('cashout')->insert($data);

        $result = $app->order->unify([
            'body' => '充值' . $data_array['money'] . '元',
            'out_trade_no' => $order,
            // 'response_type' => 'array',
            'total_fee' => $data_array['money'] * 100,//测试
            'notify_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/api/payCall/payUser',
            'trade_type' => 'JSAPI',
            'openid' => $openid,
        ]);
        $jssdk = $app->jssdk;
        $config = $jssdk->bridgeConfig($result['prepay_id'], false);
        if ($config) {
            return ['code' => '1', 'msg' => '调用成功', 'data' => $config];
        } else {
            return ['code' => '2', 'msg' => '调用失败', 'data' => $config];
        }

    }


    /*
     * 开通vip
     * */
    public function opens($data_array)
    {
        // 获取开通会员的信息
        $vip = Db::name('vip')->where('id', $data_array['vip_id'])->find();
        // 调用config
        $config = config('wechat_pay');
        $app = Factory::payment($config);
        // 生成数据
        $end_time = time() + $vip['day'] * 86400;
        // 生成订单编号
        $order_id = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
        $data = ['order_id' => $order_id, 'user_id' => $data_array['user_id'], 'vip_id' => $vip['id'], 'money' => $vip['price'], 'status' => 1, 'start_time' => time(), 'end_time' => $end_time, 'create_time' => time()];
        $user = Db::name('user')->where('id', $data_array['user_id'])->field('money,openid')->find();

        $uv = Db::name('user_vip')->where(['user_id' => $data_array['user_id'], 'is_delete' => 1, 'status' => 2])->find();

        // type : 1：余额支付，2：微信支付
        if ($data_array['type'] == 1) {
            if ($user['money'] < $vip['price']) return ['msg' => '余额不足,请充值', 'data' => '', 'code' => 0];
            $data['status'] = 2;
            Db::startTrans();
            try {
                if ($uv) {
                    $data['start_time'] = time();
                    $data['end_time'] = $uv['end_time'] + ($vip['day'] * 86400);
                    Db::name('user_vip')->where(['user_id' => $data_array['user_id'], 'is_delete' => 1])->update(['is_delete' => 2]);
                } else {
                    $data['start_time'] = time();
                    $data['end_time'] = $end_time;
                }
                $updates = ['is_vip' => 1, 'money' => $user['money'] - $vip['price']];
                Db::name('user')->where('id', $data_array['user_id'])->update($updates);
                Db::name('user_vip')->insert($data);
                Db::commit();
                return ['msg' => '开通成功', 'data' => '', 'code' => 1];
            } catch (\Exception $exception) {
                Db::rollback();
                return ['msg' => '开通失败', 'data' => '', 'code' => 0];
            }
        } else {
            Db::name('user_vip')->insert($data);
            $result = $app->order->unify([
                'body' => '开通会员' . $vip['price'] . '元',
                'out_trade_no' => $order_id,
                // 'response_type' => 'array',
                'total_fee' => $vip['price'] * 100,
                'notify_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/api/payCall/openUser',
                'trade_type' => 'JSAPI',
                'openid' => $user['openid'],
            ]);

            Log::write('https://' . $_SERVER['HTTP_HOST'] . '/api/payCall/openUser');
            $jssdk = $app->jssdk;
            $config = $jssdk->bridgeConfig($result['prepay_id'], false);
//            if ($result['return_code'] == "SUCCESS" && $result['return_msg'] == "OK"){
            if ($config) {
                return ['msg' => '开通成功', 'code' => 1, 'data' => $config];
            } else {
                return ['msg' => '开通失败', 'code' => 0, 'data' => $config];
            }
        }
    }

    /*
     * 团长信息
     * */
    public function teams($data_array)
    {
        $url = config('fastadmin.api_url');
        $user = Db::name('user')->where('id', $data_array['user_id'])->field('id as user_id,nickname,avatar,status,mobile,money as rebate,qrcode')->find();
        if ($user['status'] !== 1) return ['msg' => '不是团长,还不能登录', 'data' => '', 'code' => 0];
        // 下级
        $u_pid = Db::name('user')->where('pid', $user['user_id'])->value('pid');
        // 下下级信息
        $pid = Db::name('user')->where('pid', $u_pid)->value('id');
        // 下级信息
        $count1 = Db::name('user')->where('pid', $data_array['user_id'])->count();
        // 下下级信息
        $count2 = Db::name('user')->where('pid', $pid)->count();
        $user['sum'] = $count1 + $count2;
        if ($user['qrcode']) {
            $user['qrcode'] = $url . '/' . $user['qrcode'];
        } else {
            $user['qrcode'] = "";
        }
        if ($user) {
            return ['msg' => '查询成功', 'data' => $user, 'code' => 1];
        } else {
            return ['msg' => '暂未查到', 'data' => $user, 'code' => 1];
        }
    }


    /*
     * 提现记录
     * */
    public function cashOuts($data_array)
    {
        $page = $data_array['page'] ? $data_array['page'] : 1;
        $data = Db::name('cashout')
            ->where(['user_id' => $data_array['user_id'], 'state' => 2, 'form' => 1])
            ->field('money,type,status,content,create_time')
            ->page($page, 13)
            ->select();
        if ($data) {
            foreach ($data as &$val) {
                $val['create_time'] = date('Y-m-d H:i', $val['create_time']);
            }
        }

        return $data;
    }

    /*
     * 我的团队
     * */
    public function groups($data_array)
    {
        $page = $data_array['page'] ? $data_array['page'] : 1;
        // 下级信息
        $user = Db::name('user')
            ->where('pid', $data_array['user_id'])
            ->field('id as sub_user_id,nickname,avatar')
            ->page($page, 12)
            ->select();
        foreach ($user as &$val) {
            $val['money'] = Db::name('user_consume')->where(['user_id' => $data_array['user_id'], 'sub_user_id' => $val['sub_user_id'], 'type' => 3])->sum('money');
        }
        return $user;
    }


    /*
     * 团队-我的明细
     * */
    public function mys($data_array)
    {
        // 团长 user_id，sub_user_id
        $page = $data_array['page'] ? $data_array['page'] : 1;
        $user = Db::name('user')->where(['id' => $data_array['sub_user_id']])->field('nickname,avatar')->find();
        // 金额
        $money = Db::name('user_consume')->where(['user_id' => $data_array['user_id'], 'sub_user_id' => $data_array['sub_user_id'], 'type' => 3])->sum('money');
        // 返利明细
        $detailed = Db::name('user_consume')
            ->where(['user_id' => $data_array['user_id'], 'sub_user_id' => $data_array['sub_user_id'], 'type' => 3])
            ->field('update_time', true)
            ->page($page, 10)
            ->select();
        if ($detailed) {
            foreach ($detailed as $val) {
                $val['create_time'] = date('Y-m-d H:i', $val['create_time']);
            }
        }
        $user['money'] = $money;
        $res = ['user' => $user, 'detailed' => $detailed];
        return $res;
    }


    /*
     * 团长提现
     * */
    public function teamCashOuts($data_array)
    {
        if (!$data_array['money']) return ['msg' => '请输入金额', 'data' => '', 'code' => 0];
        if (!is_numeric($data_array['money'])) return ['msg' => '输入格式不正确', 'data' => '', 'code' => 0];
        $user = Db::name('user')->where('id', $data_array['user_id'])->field('rebate,nickname,status')->find();
        // 判断提现金额是否充足
        if ($user['rebate'] < $data_array['money']) return ['msg' => '余额不足', 'data' => '', 'code' => 0];
        // 生成保存的数据
        if ($data_array['type'] == 1) {
            $data_array['bank_card_id'] = 0;
        } elseif ($data_array['type'] == 2 && !$data_array['bank_card_id']) {
            return ['msg' => '银行卡不能为空', 'data' => '', 'code' => 0];
        }
        $state = $user['status'] == 1?2:1;
        $data = ['user_id' => $data_array['user_id'], 'nickname' => $user['nickname'], 'money' => $data_array['money'], 'type' => $data_array['type'], 'bank_card_id' => $data_array['bank_card_id'], 'status' => $state, 'state' => $user['state'], 'form' => 1, 'create_time' => time(), "content" => "提现记录"];
        Db::startTrans();
        try {
            Db::name('cashout')->insert($data);
            Db::name('user')->where('id', $data_array['user_id'])->setDec('rebate', $data_array['money']);
            Db::commit();
            return ['msg' => '提现成功,待审核', 'data' => '', 'code' => 1];
        } catch (Exception $exception) {
            Db::rollback();
            return ['msg' => '提现失败', 'data' => '', 'code' => 0];
        }

    }


    /**
     * 判斷是否是会员
     * @param $user_id
     */
    static function userVip($user_id, $order_id)
    {
        $user = Db::name('user')->where('id', $user_id)->value('is_vip');
        $order = Db::name('order')->where('order_id', $order_id)->value('money');
        // 判断是会员
        if ($user == 1) {
            $user_refund = Db::name('user_refund_amount')->where('user_id', $user_id)->find();
            if ($user_refund) {
                Db::name('user_refund_amount')->where('user_id', $user_id)->setInc('money', $order);
            } else {
                $res = [
                    'user_id' => $user_id,
                    'money' => $order,
                    'refund_amount' => 0,
                    'create_time' => time(),
                    'update_time' => time()
                ];
                Db::name('user_refund_amount')->insert($res);
            }
        }
    }

    /*
     *
     * 判断是否是团长$user_id,$order_id
     * */
    static function item($user_id, $order_id)
    {

        // 获取一二级分享的百分比
        $one = Db::name('config')->where('id', 34)->value('value');
        // 截取字符串
        // 查找上级
        $pid = Db::name('user')->where('id', $user_id)->value('pid');

        // 存在再找上级
        if ($pid) {
            // 一级返利
            $status = Db::name('user')->where('id', $pid)->value('status');
            // 存在
            if ($status) {
                $order = Db::name('vip_card_order')->where(['order_id' => $order_id])->field('money')->find();
                $money = round($order['money'] * $one / 100, 3);
                $consume = ['user_id' => $pid, 'sub_user_id' => $user_id, 'type' => 3, 'status' => 0, 'money' => $money, 'content' => '会员卡金额返利', 'create_time' => time()];
                Db::name('user')->where('id', $pid)->setInc('money', $money);
                Db::name('user_consume')->insert($consume);
            }
        }
    }


    /*
     * 生成记录
     * */
    static public function log($user_id, $order_id)
    {
        $order = Db::name('order')->where(['order_id' => $order_id, 'status' => 2])->field('money,num')->find();

        $consume = [
            'user_id' => $user_id,
            'sub_user_id' => 0,
            'type' => 4,
            'status' => 2,
            'money' => $order['money'],
            'content' => '微信购买',
            'state' => 1,
            'create_time' => time()
        ];
        Db::name('user_consume')->insert($consume);
    }


    /*
      * 团长提现返参
      * */
    public function teamCashOutResults($data_array)
    {
        // 余额
        $rebate = Db::name('user')->where('id', $data_array['user_id'])->value('rebate');
        $usable = Db::name('user')->where('id', $data_array['user_id'])->value('rebate');
        $res = ['rebate' => $rebate, 'usable' => $usable];
        return $res;
    }


    /*
     * 银行卡列表
     * */
    public function bankCards($data_array)
    {
        $page = $data_array['page'] ? $data_array['page'] : 1;
        $field = ['bank_card_name,bank_card'];
        $order = ['create_time desc'];
        $bank_card = Db::name('user_bank_card')
            ->where(['user_id' => $data_array['user_id']])
            ->field($field)
            ->order($order)
            ->page($page, 10)
            ->select();
        return $bank_card;
    }


    /*
     * 添加银行卡
     * */
    public function addBanks($data_array)
    {
        if (!$data_array['name']) return ['msg' => '请输入姓名', 'data' => '', 'code' => 0];
        if (!$data_array['card_id']) return ['msg' => '请输入身份证', 'data' => '', 'code' => 0];
        if (!$data_array['bank_card']) return ['msg' => '请输入银行卡', 'data' => '', 'code' => 0];
        if (!$data_array['bank_card_name']) return ['msg' => '请输入开户行', 'data' => '', 'code' => 0];
        if (!$data_array['phone']) return ['msg' => '请输入手机号', 'data' => '', 'code' => 0];
        if (!preg_match('/^1[3456789]\d{9}$/', $data_array['phone']))
            return ['msg' => '手机号格式不正确', 'data' => '', 'code' => 0];
        // 生成数据
        $data = ['user_id' => $data_array['user_id'], 'name' => $data_array['name'], 'card_id' => $data_array['card_id'], 'bank_card' => $data_array['bank_card'], 'bank_card_name' => $data_array['bank_card_name'], 'phone' => $data_array['phone'], 'create_time' => time()];
        $res = Db::name('user_bank_card')->insert($data);
        if ($res) {
            return ['msg' => '添加成功', 'data' => '', 'code' => 1];
        } else {
            return ['msg' => '添加失败', 'data' => '', 'code' => 0];
        }
    }


    /*
     * 爱心值规则
     * */
    public function rules()
    {
        $title = Db::name('config')->where('id', 19)->value('value');
        return $title;
    }


    /*
     * 地址
     * */
    public function addressReturns($data_array)
    {
        $data = Db::name('user_address')->where(['user_id' => $data_array['user_id'], 'status' => 2])->field('create_time,update_time', true)->find();
        return $data;
    }


    /*
     * 是否是团长
     * */
    public static function isItem($params)
    {
        // $params['id'] = 56;
        // $params['money'] = 100;
        $tc = Db::name('config')->where(['id' => 34])->value('value');
        $status = Db::name('user')->where('id', $params['id'])->value('status');
        if ($status == 1) {
            $money = $params['money'] * ($tc / 100);
            Db::name('user')->where('id', $params['id'])->setInc('money', $money);
            $time = time();
            $data = [
                'user_id' => $params['id'],
                'sub_user_id' => 0,
                'type' => 3,
                'status' => 1,
                'money' => $money,
                'content' => '团长提成',
                'create_time' => $time,
                'update_time' => $time,
            ];
            Db::name('user_consume')->insert($data);
        }
    }


    /**
     * 获取头像
     * @param string $value
     * @param array $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int $money 余额
     * @param int $user_id 会员ID
     * @param string $memo 备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int $score 积分
     * @param int $user_id 会员ID
     * @param string $memo 备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }


    /*
   * 微信小程序消息订阅
  */
    public function actionSubmessage($order_id)
    {
        // 查询订单信息
        $order = Db::name('order')->where('order_id', $order_id)->field('order_id,user_id,pay_time,money,name,title')->find();

        // 查询用户信息
        $user = Db::name('user')->where('id', $order['user_id'])->field('nickname,openid')->find();
        $config = config('mini_program');
        //配置appid
        $appid = $config['app_id'];
        //配置appscret
        $secret = $config['secret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;

        //获取access_token
        $access_token = $this->geturl($url)["access_token"];

        $urlz = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $access_token;
        //模板id
        $template_id = "dQLcxSyZm5l1X3lJMwbqQeAQUJSTvXIE7vMZ2LhhtDM";
        $data = [];
        //接收者（用户）的 openid
        $data['touser'] = $user['openid'];
        //所需下发的订阅模板id
        $data['template_id'] = $template_id;
        //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
        $data['page'] = "pages/index/index";

        //模板内容 phrase date thing 这些类型有字符长短要求，注意看文档
        $data['data'] = [
            "phrase2" => ['value' => $order_id],
            "phrase6" => ['value' => $order['pay_time']],
            "date14" => ['value' => $order['money']],
            "date8" => ['value' => $order['name'] . $order['title']],
            'thing18' => ['value' => '您已下单成功']
        ];
        //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        // $data['miniprogram_state'] = 'developer';
        $data['miniprogram_state'] = 'trial';
        $dat = $this->posturl($urlz, $data);

        return ['msg' => '添加成功', 'data' => $dat, 'code' => 1];

    }


    /*
    * curl get请求封装,返回json数据格式数据
    */
    public function geturl($url)
    {
        $headerArray = array("Content-type:application/json;", "Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return $output;
    }


    /*
     * curl post请求封装,返回json数据格式数据
    */
    public function posturl($url, $data)
    {
        $data = json_encode($data);
        $headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output, true);
    }


}
